package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;


import model.GroceryListDao;
import model.NutritionItem;

/**
 * The Nutrition panel
 * @author Lawrence Grass, Kevin Hedglin
 */
@SuppressWarnings("serial")
public class NutritionPanel extends JPanel implements ActionListener
{
	
	private GroceryListFrame frame;
	
	private JPanel nutritionView;
	
	private GroceryListDao dao;
	
	
	public NutritionPanel(GroceryListFrame frame, GroceryListDao dao)
	{
		super();
		this.dao = dao;
		this.frame = frame;
		this.setLayout(new BorderLayout());
		
		listSetup();
		JScrollPane sp = new JScrollPane(nutritionView);
		sp.setPreferredSize(new Dimension(380, 550));
		this.add(sp);
		
		//sets up the controls to manipulate the list
		this.add(controlsSetup(), BorderLayout.SOUTH);
	}
	
	/**
	 * helper method for the list panel
	 * @return the list panel
	 */
	private JPanel listSetup(){
		nutritionView = new JPanel();
		refreshItemsList();
		return nutritionView;
	}
	
	/**
	 * helper method for the controls panel
	 * @return the controls panel
	 */
	private JPanel controlsSetup(){
		JPanel controlsPanel = new JPanel();
		controlsPanel.setPreferredSize(new Dimension(200, 50));
		controlsPanel.setBackground(Color.gray);
		JButton back = new JButton("Go Back ");
		back.addActionListener(this);
		back.setPreferredSize(new Dimension(120, 20));
		controlsPanel.add(back);
		JButton addItem = new JButton("Add Item");
		addItem.addActionListener(frame);
		addItem.setPreferredSize(new Dimension(120, 20));
		controlsPanel.add(addItem);
		return controlsPanel;
	}
	
	public void refreshItemsList(){
		nutritionView.removeAll();
		try {
			List<NutritionItem> list = dao.getNutrition();
			for(NutritionItem item: list){
				JPanel row = new JPanel();
				row.setPreferredSize(new Dimension(400, 60));
				JLabel top_nutrition = new JLabel(item.toStringTop());
				JLabel bottom_nutrition = new JLabel(item.toStringBottom());
				row.add(top_nutrition);
				row.add(bottom_nutrition);
				nutritionView.add(row);
				nutritionView.setPreferredSize(new Dimension(380, list.size() * 70));
			}
			
		} catch (Exception e) {
			//Do nothing?
			e.printStackTrace();
		}
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		frame.refreshCards();
		frame.goMain();
	}
	
	
}